#include "googlemtransplugin.h"

GoogleMTransPlugin::GoogleMTransPlugin(){
    QString seed = this->toString();
    ID = QCryptographicHash::hash( seed.toAscii(), QCryptographicHash::Md5);

    downloader = new Downloader(this);
    checked = true;

    connect(downloader, SIGNAL(errorOccured(const QString &)),
            this, SLOT(catchError(const QString&)));

    //>>>>>>>>
    //! connecting the downloader.done() signal to member slot finished()
    connect(downloader, SIGNAL(done(const QStringList&)),
            this, SLOT(finished(const QStringList&)));
    //<<<<<<<<

    /*
     translate.google.com/translate_t?langpair=auto|hu&text=I had a good meal
     */

    searchKey=QString("text");
    url.setHost("translate.google.com");
    url.setPath("/translate_t");





    QStringList queryLang( QStringList()
                           <<"auto"<<"sq"<<"en"<<"ar"<<"bg"<<"cs"<<"da"
                           <<"et"<<"tl"<<"fi"<<"fr"<<"gl"<<"el"<<"iw"
                           <<"hi"<<"nl"<<"hr"<<"id"<<"ja"<<"ca"<<"zh-CN"
                           <<"ko"<<"pl"<<"lv"<<"lt"<<"hu"<<"mt"<<"de"
                           <<"no"<<"it"<<"ru"<<"pt"<<"ro"<<"es"<<"sv"
                           <<"sr"<<"sk"<<"sl"<<"th"<<"tr"<<"uk"<<"vi"
                         );

    LangList llst = ( LangList()
                           << AAA << ALB << ENG << ARA << BGR << CZH << DEN
                           << EST << FLP << FIN << FRA << GAL << GRE << HEB
                           << HIN << NED << HRV << IND << JAP << CAT << ZHCN
                           << KOR << POL << LTV << LIT << HUN << MAL << GER
                           << NOR << ITA << RUS << POR << ROM << ESP << SWE
                           << SER << SLK << SLV << THI << TUR << UKR << VIE
                           );

    int i=0;
    foreach( Lang lng, llst ) {
        //!populating LangHash
        supportedLangs[lng] = lngConv.lang2Str(lng);
    }
}




bool GoogleMTransPlugin::search(const State &s) {
        StrPairList actQuery(StrPairList()
                             << qMakePair("langpair",
                                          supportedLangs[s.dict.first]+"|"+
                                          supportedLangs[s.dict.second]
                                         )
                             );
        actQuery.append( qMakePair( searchKey, s.word ) );
        qDebug() <<"ACTQUERY: "<< actQuery;

        url.setQueryItems(actQuery);
        url.setScheme("http");
        qDebug()<<"DICTIONARIES_URL: "<<url.toString();

        downloader->setUrl(url);
        downloader->download();

        return true;
}

void GoogleMTransPlugin::finished(const QStringList &lst ) {
    qDebug() << "In function "+QString(Q_FUNC_INFO);


    QList< QRegExp > rxlist;
    QRegExp nl("\n");
    QRegExp strong("<strong>");
    QRegExp endstrong("</strong>");
    QRegExp andnbsp(",&nbsp");
    QRegExp remdfn("</dfn>\\s");
    QRegExp dfn("\\s<dfn>\\s");
    QRegExp desc("<span\\sclass=\"desc\">");

    //*	A QRegExp list is used, to remove unneeded junk from result
    //* << QRegExp("(^.+)<!--result-->") << QRegExp("<!--/result-->(.+$)")

    rxlist << nl <<strong << endstrong <<andnbsp<<remdfn;

    //*	&lst is a QStringList of downloaded html sites, but we only downloaded one site, so we need lst.first()
    QString result = utils::remove( lst.first(), rxlist);

    result = result.replace(dfn, ";");
    result = result.remove(desc);
    result = result.replace("《", "(");
    result = result.replace("》", ")");
    result = result.replace("</span> ;", ";");

    QFile file("google.txt", this);;
    file.open(QIODevice::WriteOnly);
    QTextStream out(&file);
    out<<result;
    file.close();

    QRegExp first("<h2\\sclass=\"wd\">\\s([^<>/\"]+)\\s<span");
    QRegExp second;
    if (singleMode){
        second.setPattern("<span\\sclass=\"phn\">\\s([^<>/\"]+)\\s</span");
    }else second.setPattern("class=\"mn\">\\s([^<>/\"]+)(</span>)?\\s</?span");
    first.setMinimal(true);
    second.setMinimal(true);

    Parser parser( result, first, second );
    hash=parser.parse("1");
    first.setPattern("<li>\\s([^<>/\"]+)(</span>)?\\s<br>;");
    second.setPattern("<br>;([^<>/\"]+)\\s</");
    parser.setRegExp(first,second);
    hash.add(parser.parse(";"));
    qDebug("hash.debug()>>>>");
    hash.debug();
    qDebug("<<<<hash.debug()");

    //if ( !pairList.isEmpty() && pairList.last().second.split(" ").first() == "=>" ) pairList.removeLast(); // remove junk

    emit done( hash, url.host() );
}

const LangHash GoogleMTransPlugin::getLangHash() const{
    return supportedLangs;
}

bool GoogleMTransPlugin::isChecked(){
    return checked;
}

QString GoogleMTransPlugin::description(){
    QStringList values=supportedLangs.values();
    values.sort();
    return values.join(", ");
}

void GoogleMTransPlugin::setChecked(bool opt){
    checked = opt;
}

void GoogleMTransPlugin::catchError(const QString &msg ){
    emit errorOccured( msg );
}



Q_EXPORT_PLUGIN2(googlemtransplugin, GoogleMTransPlugin)
